package com.ydzt.fanka.server.utils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.log.LoggerFanka;

public class NetUtil {
	static Logger logger = Logger.getLogger(NetUtil.class.getName());
	public static int MAX_MSG_BUF = 10000;

	/**
	 * 多IP处理，可以得到最终ip
	 * 
	 */
	public static String getIp() {
		return InitData.OWNER_IP;
	}

	/*
	 * 发送包 根据消息处理类型和下游节点IP/PORT
	 */
	public static int synSendMsg(byte[] sendpkg) {
		String env_ip = null;
		String env_port = null;
		int statu = -1;
		int offset = 6;
		int port = 0;

		byte[] sendpkgLength = new byte[2];
		System.arraycopy(ByteConvert.shortToBytes((short) sendpkg.length), 0,
				sendpkgLength, 0, 2);
		byte[] waitSendPkg = new byte[sendpkg.length + 2];
		System.arraycopy(sendpkgLength, 0, waitSendPkg, 0, 2);
		System.arraycopy(sendpkg, 0, waitSendPkg, 2, sendpkg.length);

		// 取sendpkg 中的 receiver port msgMgrType
		byte[] receiverByte = new byte[4];
		byte[] portByte = new byte[2];
		byte[] msgMgrType = new byte[1];
		System.arraycopy(
				ByteConvert.str2BcdNormal(InitData.nodeType + "000000"), 0,
				sendpkg, 2, 4);
		System.arraycopy(sendpkg, offset, receiverByte, 0, 4);
		offset += 4;

		System.arraycopy(sendpkg, offset, portByte, 0, 2);
		offset += 2;

		System.arraycopy(sendpkg, offset, msgMgrType, 0, 1);
		offset += 1;
		Socket socket = null;
		try {
			try {
				if (msgMgrType[0] == 0x02 || msgMgrType[0] == 0x03) {
					String tmp = InitData.getInstance().getSupplierMap()
							.get("00000000");
					if (tmp != null) {
						env_ip = tmp.split(":")[0];
						env_port = tmp.split(":")[1];
					} else {
						logger.info("找不到节点00000000对应的IP,检查数据库是否配置有节点00的IP和地址");
					}
				}
				if (msgMgrType[0] == 0x00 || msgMgrType[0] == 0x01) {
					String tmp = InitData.getInstance().getSupplierMap()
							.get(ByteConvert.bcd2Str(receiverByte));
					if (tmp != null) {
						env_ip = tmp.split(":")[0];
						env_port = tmp.split(":")[1];
					} else {
						logger.info("找不到节点" + ByteConvert.bcd2Str(receiverByte) + "对应的IP,检查数据库是否配置有节点00的IP和地址");
					}
				}

				if (Integer.parseInt(env_port) < 0) {
					port = 65536 + Integer.parseInt(env_port);
				} else {
					port = Integer.parseInt(env_port);
				}
				try {
					logger.info("尝试与" + env_ip + "/" + port + "建立连接!");
					socket = new Socket(env_ip, port);
					if (socket.isConnected() == true) {
						try {
							OutputStream netOut = socket.getOutputStream();
							DataOutputStream doc = new DataOutputStream(netOut);

							doc.write(waitSendPkg);
							logger.info(LoggerFanka.dumpBin(waitSendPkg));
							doc.close();
							socket.close();
							statu = 0;
						} catch (IOException e) {
							logger.error("对IP:" + env_ip + "在端口" + env_port
									+ "上发送报文失败");
							logger.error(e.getMessage(), e);
						} finally {
							if (socket != null) {
								try {
									socket.close();
								} catch (IOException e) {
									logger.error("关闭socket失败");
									logger.error(e.getMessage(), e);
								}
							}
						}
					} else {
					}
					logger.info("与" + env_ip + "在端口" + port + "上建立socket连接");
				} catch (ConnectException e) {
					logger.error("建立与" + env_ip + "/" + port + "的连接失败!"
							+ e.getMessage());
				}

			} catch (NumberFormatException e1) {
				logger.error("与" + env_ip + "在端口" + port
						+ "上建立socket连接失败  端口转int类型失败");
				logger.error(e1.getMessage(), e1);
			}
		} catch (UnknownHostException e1) {
			logger.error("与" + env_ip + "在端口" + port + "上建立socket连接失败 获取主机失败");
			logger.error(e1.getMessage(), e1);
		} catch (IOException e1) {
			logger.error("与" + env_ip + "在端口" + port
					+ "上建立socket连接失败  socket IO错误");
			logger.error(e1.getMessage(), e1);
		}

		return statu;
	}
}
